package com.molichuxing.gateway.bff.car.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.framework.utils.RedisUtil;
import com.molichuxing.gateway.bff.car.convertor.Convert;
import com.molichuxing.gateway.bff.car.entity.request.create.MaintenanceConfigCreateVo;
import com.molichuxing.gateway.bff.car.entity.request.create.MaintenanceLogCreateVo;
import com.molichuxing.gateway.bff.car.entity.request.modify.MaintenanceConfigModifyVo;
import com.molichuxing.gateway.bff.car.entity.request.modify.MaintenanceLogModifyVo;
import com.molichuxing.gateway.bff.car.entity.response.*;
import com.molichuxing.gateway.bff.car.services.MaintenanceBffService;
import com.molichuxing.gateway.exception.StatisticsRedisKey;
import com.molichuxing.gateway.property.CarCheckClientEnum;
import com.molichuxing.gateway.property.StockEnum;
import com.molichuxing.gateway.utils.TokenUtil;
import com.molichuxing.gateway.utils.entity.UserEntity;
import com.molichuxing.services.business.dto.response.*;
import com.molichuxing.services.business.service.*;
import com.molichuxing.services.infrastructure.dto.request.create.MaintenanceConfigCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.MaintenanceLogCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.MessageCenterCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.NotifyPushCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.MaintenanceConfigModifyDto;
import com.molichuxing.services.infrastructure.dto.response.CarDto;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.dto.response.response.AccountDto;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 车辆检验bff
 *
 * @author xuelin yi
 */
@Service("maintenanceBffService")
public class MaintenanceBffServiceImpl implements MaintenanceBffService {

    private static final Logger logger = LoggerFactory.getLogger(MaintenanceBffServiceImpl.class);

    @Resource
    private MaintenanceBizService maintenanceBizService;

    @Resource
    private VehicleBizService vehicleBizService;

    @Resource
    private StockCarBizService stockCarBizService;

    @Resource
    private StoreBizService storeBizService;

    @Resource
    private UserBizService userBizService;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private CarService carService;

    @Resource
    private OrderBizService orderBizService;

    @Resource
    private MaintenanceLogService maintenanceLogService;

    @Resource
    private MaintenanceService maintenanceService;

    @Resource
    private MaintenanceConfigService maintenanceConfigService;

    @Resource
    private UserService userService;

    @Resource
    private IovCarService iovCarService;

    @Resource
    private MessageTemplateService messageTemplateService;

    @Resource
    private SmsBizService smsBizService;

    @Resource
    private MessageCenterService messageCenterService;

    @Resource
    private NotifyPushService notifyPushService;

    @Resource
    private DealerDetailService dealerDetailService;

    @Resource
    private AccountService accountService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private VehiclePictureService vehiclePictureService;


    @Override
    public Paged<MaintenanceBizVo> getMaintenancePage(Map<String, Object> mapParam, Integer pageNum, Integer pageSize) throws Exception {

        Integer totalStartMileage = ObjectCastUtil.castInteger(mapParam.get("totalStartMileage"));
        Integer totalEndMileage = ObjectCastUtil.castInteger(mapParam.get("totalEndMileage"));
        if (totalStartMileage != null || totalEndMileage != null) {
            long start = System.currentTimeMillis();
            List<Integer> carIdList = getCarIdList(totalStartMileage, totalEndMileage);
            long end = System.currentTimeMillis();
            long time = end - start;
            logger.info("获取车辆id查询时间：" + time);

            if (null == carIdList || carIdList.size() < 1) {
                carIdList = new ArrayList<>();
                carIdList.add(0);
            }
            mapParam.put("carIdList", carIdList);
        }

        Paged<MaintenanceBizDto> paged = maintenanceBizService.getMaintenancePage(mapParam, pageNum, pageSize);
        Paged<MaintenanceBizVo> page = Convert.toMaintenanceBizVo(paged);
        List<Integer> carIds = getCarIds(page.getList());
        Map<Integer, String> vehicleMap = null;
        if (null != carIds) {
            vehicleMap = vehicleBizService.getVehicleFullName(carIds);
        }
        getVehicleStock(page.getList(), vehicleMap);


        return page;
    }

    private List<Integer> getCarIdList(Integer totalStartMileage, Integer totalEndMileage) throws Exception {
        if (null == totalStartMileage || null == totalEndMileage) {
            return null;
        }

        long carStart = System.currentTimeMillis();
        List<CarDto> carDtoList = getCarList();
        long carEnd = System.currentTimeMillis();
        long carTime = carEnd - carStart;
        logger.info("查询车辆时间：" + carTime);

        if (null == carDtoList || carDtoList.size() < 1) {
            return null;
        }

        long mileageStart = System.currentTimeMillis();
        List<IovMileageDto> mileageList = iovCarService.getMileage();
        long mileageEnd = System.currentTimeMillis();
        long mileageTime = mileageEnd - mileageStart;
        logger.info("查询车联网获取里程时间：" + mileageTime);
        if (null == mileageList || mileageList.size() < 1) {
            return null;
        }

        if (totalStartMileage == 0 || carDtoList.size() < mileageList.size()) {
            return getCarIdListByCarList(carDtoList, mileageList, totalStartMileage, totalEndMileage);
        } else {
            return getCarIdListByMileageList(carDtoList, mileageList, totalStartMileage, totalEndMileage);
        }
    }

    private List<CarDto> getCarList() {
        Map<String, String> map = redisUtil.hgetAll(StatisticsRedisKey.CAR_INFO);
        if (null == map || map.size() < 1) {
            List<Integer> businessTypeList = new ArrayList<>();
            businessTypeList.add(CarsBusinessTypeEnum.NO_BUSINESS.getValue());
            businessTypeList.add(CarsBusinessTypeEnum.EXCLUSIVE.getValue());
            businessTypeList.add(CarsBusinessTypeEnum.SUBSCRIBE.getValue());
            return carService.getCarsByBusinessTypeList(businessTypeList);
        }

        List<CarDto> carDtoList = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String value = entry.getValue();
            carDtoList.add(JSONObject.parseObject(value, CarDto.class));
        }
        return carDtoList;
    }

    private List<Integer> getCarIdListByCarList(List<CarDto> carDtoList, List<IovMileageDto> mileageList,
                                                Integer totalStartMileage, Integer totalEndMileage) {
        Map<String, IovMileageDto> mileageMap =
                mileageList.stream().collect(Collectors.toMap(IovMileageDto::getVin, iovMileageDto -> iovMileageDto));

        List<Integer> carIdList = new ArrayList<>();
        for (CarDto carDto : carDtoList) {
            String vin = carDto.getVin();
            Integer carId = carDto.getId();

            if (StringUtils.isBlank(vin) || null == carId) {
                continue;
            }

            IovMileageDto iovMileageDto = mileageMap.get(vin);
            if (null == iovMileageDto) {
                continue;
            }

            Integer odo = iovMileageDto.getOdo();
            if (null == odo) {
                odo = 0;
            }

            if (odo >= totalStartMileage && odo <= totalEndMileage) {
                carIdList.add(carId);
            }
        }
        return carIdList;
    }

    private List<Integer> getCarIdListByMileageList(List<CarDto> carDtoList, List<IovMileageDto> mileageList,
                                                    Integer totalStartMileage, Integer totalEndMileage) {
        Map<String, CarDto> carMap =
                carDtoList.stream().collect(Collectors.toMap(CarDto::getVin, carDto -> carDto));

        List<Integer> carIdList = new ArrayList<>();
        for (IovMileageDto iovMileageDto : mileageList) {
            String vin = iovMileageDto.getVin();
            if (StringUtils.isBlank(vin)) {
                continue;
            }

            CarDto carDto = carMap.get(vin);
            if (null == carDto) {
                continue;
            }

            Integer carId = carDto.getId();
            Integer odo = iovMileageDto.getOdo();
            if (null == odo) {
                odo = 0;
            }

            if (odo >= totalStartMileage && odo <= totalEndMileage) {
                carIdList.add(carId);
            }
        }
        return carIdList;
    }

    @Override
    public List<MaintenanceRecordVo> getMaintenanceByCarId(Integer carId) throws Exception {
        List<MaintenanceRecordBizDto> maintenanceRecordList = maintenanceBizService.getMaintenanceByCarId(carId);
        List<MaintenanceRecordVo> result = Convert.toMaintenanceRecordVo(maintenanceRecordList);
        if ((null != result) && (result.size() > 0)) {
            for (MaintenanceRecordVo maintenanceRecordVo : result) {
                //用户
                if (maintenanceRecordVo.getOperationType() == 2) {
                    UserBizDto userBizDto = userBizService.getUser(Integer.parseInt(maintenanceRecordVo.getOperationId()));
                    if (null != userBizDto) {
                        maintenanceRecordVo.setRealName(userBizDto.getRealName());
                        maintenanceRecordVo.setUserName(userBizDto.getName());
                        maintenanceRecordVo.setUserPhone(userBizDto.getPhone());
                        maintenanceRecordVo.setIdNumber(userBizDto.getIdNumber());
                    }
                } else {
                    maintenanceRecordVo.setUserName(CarCheckClientEnum.MOLI.getName());
                }
            }
        }
        return result;
    }

    @Override
    public MaintenanceDetailVo getMaintenanceById(Integer id) throws Exception {
        MaintenanceDetailBizDto maintenanceDetail = maintenanceBizService.getMaintenance(id);
        MaintenanceDetailVo maintenanceDetailVo = Convert.toMaintenanceDetailVo(maintenanceDetail);
        if (null != maintenanceDetailVo) {
            String vehicleName = vehicleBizService.getVehicleName(maintenanceDetailVo.getBasic().getVehicleId());
            maintenanceDetailVo.getBasic().setVehicleName(vehicleName);
            getVehicleStock(maintenanceDetail, maintenanceDetailVo);
            // 查询车辆当前里程
            Integer currentMileage = iovCarService.getCurrentMileage(maintenanceDetailVo.getBasic().getVin());
            maintenanceDetailVo.getBasic().setTravelMileage(currentMileage);
            if (null != currentMileage && null != maintenanceDetailVo.getBasic().getMaintainableMileage()) {
                BigDecimal overMileage = new BigDecimal(currentMileage - (maintenanceDetailVo.getBasic().getMaintainableMileage().intValue()));
                if (overMileage.compareTo(new BigDecimal("0")) > 0) {
                    maintenanceDetailVo.getBasic().setOverMileage(overMileage);
                } else {
                    maintenanceDetailVo.getBasic().setOverMileage(new BigDecimal("0"));
                }
            } else {
                maintenanceDetailVo.getBasic().setOverMileage(new BigDecimal("0"));
            }

            MaintenanceInfoVo info = maintenanceDetailVo.getInfo();
            if (info != null) {
                String submitMemberName = getSubmitMemberName(maintenanceDetail);
                info.setSubmitMemberName(submitMemberName);
            }
            getRecordListSubmitMemberName(maintenanceDetailVo);
        }
        return maintenanceDetailVo;
    }

    @Override
    public MaintenanceRecordVo getMaintenanceRecordById(Integer recordId) throws Exception {
        MaintenanceLogDto maintenanceLogDto = maintenanceLogService.getMaintenanceLogById(recordId);
        MaintenanceRecordVo maintenanceRecordVo = Convert.toMaintenanceRecordDto(maintenanceLogDto);
        if (null != maintenanceRecordVo) {
            maintenanceRecordVo.setSubmitMemberName(getName(null, maintenanceRecordVo.getUserType(), maintenanceRecordVo.getUserId()));
        }
        return maintenanceRecordVo;
    }

    private void getRecordListSubmitMemberName(MaintenanceDetailVo maintenanceDetailVo) {
        List<MaintenanceRecordVo> recordList = maintenanceDetailVo.getRecordList();
        if (null == recordList || recordList.size() < 1) {
            return;
        }

        for (MaintenanceRecordVo maintenanceRecordVo : recordList) {
            String operationId = maintenanceRecordVo.getOperationId();
            Integer userType = maintenanceRecordVo.getUserType();
            Integer submitMemberId = maintenanceRecordVo.getUserId();
            Integer operationType = maintenanceRecordVo.getOperationType();
            String name = getName(operationId, userType, submitMemberId);
            maintenanceRecordVo.setSubmitMemberName(name);
            if (null != operationId) {
                String operationName = getOperationName(operationType, Integer.parseInt(operationId));
                maintenanceRecordVo.setOperationName(operationName);
            }

        }
    }


    private String getOperationName(Integer operationType, Integer submitMemberId) {
        if (operationType != null && operationType.equals(CarsOperationType.OP.getValue())) {
            if (null == submitMemberId) {
                return "";
            }
            AccountDto accountDto = accountService.getById(Integer.valueOf(submitMemberId));
            if (null == accountDto) {
                return "";
            }
            return accountDto.getRealName();
        } else {
            if (null == submitMemberId) {
                return "";
            }
            UserDto user = userService.getUser(submitMemberId);
            if (null == user) {
                return "";
            }
            return user.getRealName();
        }
    }


    private String getSubmitMemberName(MaintenanceDetailBizDto maintenanceDetail) {
        MaintenanceInfoBizDto info = maintenanceDetail.getInfo();
        if (null == info) {
            return "";
        }

        String operationId = info.getOperationId();
        Integer operationType = info.getUserType();
        Integer submitMemberId = info.getUserId();
        return getName(operationId, operationType, submitMemberId);
    }

    private String getName(String operationId, Integer operationType, Integer submitMemberId) {
        if (operationType != null && operationType.equals(CarsOperationType.OP.getValue())) {
            if (null == submitMemberId) {
                return "";
            }
            AccountDto accountDto = accountService.getById(Integer.valueOf(submitMemberId));
            if (null == accountDto) {
                return "";
            }
            return accountDto.getRealName();
        } else {
            if (null == submitMemberId) {
                return "";
            }
            UserDto user = userService.getUser(submitMemberId);
            if (null == user) {
                return "";
            }
            return user.getRealName();
        }
    }

    @Override
    public Boolean createMaintenanceLog(MaintenanceLogCreateVo maintenanceLogCreateVo) throws Exception {

        //获取当前登录用户
        UserEntity currentLoginUser = tokenUtil.getUser();
        if (null == currentLoginUser) {
            throw new Exception("用户未登录");
        }
        //根据车牌查询车辆id
        CarDto carDto = carService.getByVinLicencePlate(null, maintenanceLogCreateVo.getLicencePlate());
        if (null == carDto) {
            throw new Exception("车牌不存在");
        }
        MaintenanceLogCreateDto maintenanceLogCreateDto = new MaintenanceLogCreateDto();
        BeanUtils.copyProperties(maintenanceLogCreateVo, maintenanceLogCreateDto);
       /* //查询当前车辆是否关联用车中的订单
        CarOrderBizDto carOrderBizDto = orderBizService.getUseOrderByCar(carDto.getId(),currentLoginUser.getAccountId());
        if(null != carOrderBizDto){
            maintenanceLogCreateDto.setOrderCode(carOrderBizDto.getOrderCode());
        }*/
        maintenanceLogCreateDto.setCarId(carDto.getId());
        maintenanceLogCreateDto.setSettlementUrl(JSON.toJSONString(maintenanceLogCreateVo.getSettlementUrlList()));
        maintenanceLogCreateDto.setSubmitMemberId(currentLoginUser.getAccountId());
        // maintenanceLogCreateDto.setMaintainableDate(DateUtil.parseDate(maintenanceLogCreateVo.getMaintainableDate()).atStartOfDay());
        maintenanceLogCreateDto.setActualMaintainDate(DateUtil.parseDate(maintenanceLogCreateVo.getActualMaintainDate()));
        maintenanceLogCreateDto.setActualMaintainMileage(maintenanceLogCreateVo.getActualMaintainMileage());
        maintenanceLogCreateDto.setSubmitDate(LocalDateTime.now());
        maintenanceLogCreateDto.setPurchaseDate(carDto.getPurchaseDate());
        maintenanceLogCreateDto.setStatus(MaintenanceStatusEnum.AUDITED.getValue());
        maintenanceLogCreateDto.setUserId(currentLoginUser.getAccountId());
        maintenanceLogCreateDto.setUserType(MaintenanceUserTypeEnum.OP.getValue());
        MaintenanceDto maintenanceDto = maintenanceService.getMaintenance(maintenanceLogCreateVo.getMaintenanceId());
        if (null == maintenanceDto) {
            throw new Exception("数据不存在");
        }
        maintenanceLogCreateDto.setOrderCode(maintenanceDto.getOrderCode());
        maintenanceLogCreateDto.setMaintainableMileage(maintenanceDto.getMaintainableMileage());
        maintenanceLogCreateDto.setMaintainableDate(maintenanceDto.getMaintainableDate());
        //新增
        int ret = maintenanceLogService.createMaintenanceLog(maintenanceLogCreateDto);
        if (ret < 0) {
            logger.error("新建保养信息失败");
            throw new Exception("新建保养信息失败");
        }

        int updateResult = maintenanceService.updateMaintenanceStatusById(maintenanceLogCreateVo.getMaintenanceId(), MaintenanceStatusEnum.AUDITED);
        if (updateResult < 0) {
            logger.error("编辑保养状态失败");
            throw new Exception("编辑保养状态失败");
        }

        return true;
    }

    @Override
    public int modifyMaintenanceCheck(MaintenanceLogModifyVo modifyVo) throws Exception {
        //获取当前登录用户
        UserEntity currentLoginUser = tokenUtil.getUser();
        if (null == currentLoginUser) {
            throw new Exception("用户未登录");
        }
        modifyVo.setOperateId(currentLoginUser.getAccountId());
        try {
            MaintenanceLogDto maintenanceLogDto = maintenanceLogService.getMaintenanceLogByPId(modifyVo.getMaintenanceLogId());
            if (null == maintenanceLogDto) {
                throw new BizException("数据不存在");
            }
            CarDto carDto = carService.getCarById(maintenanceLogDto.getCarId());
            if (null == carDto) {
                throw new BizException("车辆数据不存在");
            }
            MaintenanceConfigDto maintenanceConfigDto = maintenanceConfigService.getMaintenanceConfigByVehicleId(carDto.getVehicleId());
            String phone = null;
            if (maintenanceLogDto.getUserType() == MaintenanceUserTypeEnum.USER.getValue()) {
                UserDto userDto = userService.getUser(maintenanceLogDto.getUserId());
                Map<String, MessageTemplateDto> templateMap = messageTemplateService
                        .getByKey(Arrays.asList("instation_maintenance_remind_confirm_push", "instation_maintenance_remind_confirm_message"
                                , "instation_maintenance_remind_invalid_push", "instation_maintenance_remind_invalid_message"));
                JSONObject json = new JSONObject();
                json.put("plate", carDto.getLicencePlate());
                BigDecimal mileage = maintenanceLogDto.getActualMaintainMileage().add(maintenanceConfigDto.getMileage());
                LocalDateTime dateTime = DateUtil.plus(maintenanceLogDto.getActualMaintainDate().atStartOfDay(), maintenanceConfigDto.getMaintenanceTime(), ChronoUnit.DAYS);
                if (modifyVo.getStatus() == 0) {
                    json.put("num", mileage.stripTrailingZeros().toPlainString());
                    json.put("date", dateTime.toLocalDate().toString());
                    smsBizService.sendMessage(userDto.getPhone(), SmsTemplateEnum.MAINTENANCE_CONFIRM.getValue(), json.toJSONString(), null);
                    // 发送推送
                    MessageTemplateDto messageTemplateDto = templateMap.get("instation_maintenance_remind_confirm_push");
                    String body = messageTemplateDto.getBody().replace("${licencePlate}", carDto.getLicencePlate()).
                            replace("${mileage}", mileage.stripTrailingZeros().toPlainString()).replace("${dateTime}", dateTime.toLocalDate().toString());
                    try {
                        NotifyPushCreateDto notifyPush = new NotifyPushCreateDto(Arrays.asList(userDto.getPhone()),
                                messageTemplateDto.getSubject(), messageTemplateDto.getSubject(), body, body, null, "");
                        notifyPushService.notifyPushByAlias(notifyPush);
                    } catch (Exception e) {
                        logger.error("保养(" + maintenanceLogDto.getId() + ")审核完成发送消息异常：", e);
                    }
                    // 保存消息
                    MessageTemplateDto messageTemplate = templateMap.get("instation_maintenance_remind_confirm_message");
                    String message = messageTemplate.getBody().replace("${licencePlate}", carDto.getLicencePlate()).
                            replace("${mileage}", mileage.stripTrailingZeros().toPlainString()).replace("${dateTime}", dateTime.toLocalDate().toString());
                    ;
                    MessageCenterCreateDto messageCenterCreateDto = new MessageCenterCreateDto();
                    messageCenterCreateDto.setUserId(userDto.getId());
                    messageCenterCreateDto.setTitle("保养审核结果通知");
                    messageCenterCreateDto.setMessage(message);
                    messageCenterCreateDto.setType(MessageCenterTypeEnum.MAINTENANCE_AUDIT_RESULTS_NOTICE.getValue());
                    messageCenterCreateDto.setStatus(MessageCenterStatusEnum.UNREAD.getValue());
                    messageCenterService.createMessageCenter(messageCenterCreateDto);
                } else if (modifyVo.getStatus() == 1) {
                    smsBizService.sendMessage(userDto.getPhone(), SmsTemplateEnum.MAINTENANCE_INVALID.getValue(), json.toJSONString(), null);
                    // 发送推送
                    MessageTemplateDto messageTemplateDto = templateMap.get("instation_maintenance_remind_invalid_push");
                    String body = messageTemplateDto.getBody().replace("${licencePlate}", carDto.getLicencePlate()).
                            replace("mileage", mileage + "").replace("dateTime", DateUtil.formatTime(dateTime));
                    try {
                        NotifyPushCreateDto notifyPush = new NotifyPushCreateDto(Arrays.asList(userDto.getPhone()),
                                messageTemplateDto.getSubject(), messageTemplateDto.getSubject(), body, body, null, "");
                        notifyPushService.notifyPushByAlias(notifyPush);
                    } catch (Exception e) {
                        logger.error("保养(" + maintenanceLogDto.getId() + ")审核完成发送消息异常：", e);
                    }
                    // 保存消息
                    MessageTemplateDto messageTemplate = templateMap.get("instation_maintenance_remind_invalid_message");
                    String message = messageTemplate.getBody().replace("${licencePlate}", carDto.getLicencePlate());
                    MessageCenterCreateDto messageCenterCreateDto = new MessageCenterCreateDto();
                    messageCenterCreateDto.setUserId(userDto.getId());
                    messageCenterCreateDto.setTitle("保养审核结果通知");
                    messageCenterCreateDto.setMessage(message);
                    messageCenterCreateDto.setType(MessageCenterTypeEnum.MAINTENANCE_AUDIT_RESULTS_NOTICE.getValue());
                    messageCenterCreateDto.setStatus(MessageCenterStatusEnum.UNREAD.getValue());
                    messageCenterService.createMessageCenter(messageCenterCreateDto);
                }
            }
        } catch (Exception e) {
            logger.error("发送信息失败");
        }

        return maintenanceBizService.modifyMaintenanceCheck(Convert.toMaintenanceModifyDto(modifyVo, currentLoginUser.getAccount()));
    }


    private void getVehicleStock(MaintenanceDetailBizDto maintenanceDetail, MaintenanceDetailVo maintenanceDetailVo) throws Exception {
        MaintenanceBasicBizDto basic = maintenanceDetail.getBasic();
        StockCarBaseBizDto stockCarBizDto = stockCarBizService.getStockBaseCar(maintenanceDetailVo.getBasic().getCarId());
        if (stockCarBizDto != null) {
            if (stockCarBizDto.getStockType().equals(StockCarStockTypeEnum.ENTREPOT_STORAGE.getValue())) {
                maintenanceDetailVo.getBasic().setStockName("茉莉-" + stockCarBizDto.getStockName());
                maintenanceDetailVo.getBasic().setStock(StockEnum.STOCK.getValue());
            } else {
                Integer userId = basic.getUserId();
                DealerStoreInfoBizDto dealerStoreInfoBizDto = storeBizService.getDealerStoreInfo(stockCarBizDto.getStoreId());
                if (userId != null) {
                    UserDto user = userService.getUser(userId);
                    maintenanceDetailVo.getBasic().setStockName(dealerStoreInfoBizDto.getDealerShortName() + "-" + user.getRealName());
                    maintenanceDetailVo.getBasic().setStock(StockEnum.USER.getValue());
                    maintenanceDetailVo.getBasic().setUserPhone(user.getPhone());
                } else {
                    try {
                        DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(dealerStoreInfoBizDto.getDealerId());

                        maintenanceDetailVo.getBasic().setStockName(dealerStoreInfoBizDto.getDealerShortName() + "-" + dealerStoreInfoBizDto.getStoreShortName());
                        maintenanceDetailVo.getBasic().setStock(StockEnum.DEALER.getValue());
                        maintenanceDetailVo.getBasic().setUserPhone(dealerDetailDto.getResponsiblePhone());
                    } catch (Exception e) {
                        logger.error("查询门店信息异常");
                    }
                }
            }
        }
    }

    private static List<Integer> getCarIds(List<MaintenanceBizVo> maintenanceList) {
        List<Integer> carIds = null;
        if ((null != maintenanceList) && (maintenanceList.size() > 0)) {
            carIds = new ArrayList<>();
            for (MaintenanceBizVo dto : maintenanceList) {
                carIds.add(dto.getVehicleId());
            }
        }
        return carIds;
    }

    private void getVehicleStock(List<MaintenanceBizVo> maintenanceBizVoList, Map<Integer, String> vehicleMap) throws Exception {
        List<Integer> vehicleIds = new ArrayList<>();
        if (null != maintenanceBizVoList && maintenanceBizVoList.size() > 0) {
            List<Integer> ids = new ArrayList<>();
            for (MaintenanceBizVo carDto : maintenanceBizVoList) {
                // 查询车辆当前里程
                Integer currentMileage = iovCarService.getCurrentMileage(carDto.getVin());
                carDto.setTotalMileage(currentMileage);
                ids.add(carDto.getCarId());
                carDto.setVehicleName(vehicleMap.get(carDto.getVehicleId()));
                vehicleIds.add(carDto.getVehicleId());
            }
            Map<Integer, StockCarBizDto> stockCarBizMap = stockCarBizService.getStockBaseCars(ids);
            if (null == stockCarBizMap) {
                return;
            }
            for (MaintenanceBizVo carDto : maintenanceBizVoList) {
                StockCarBizDto stockCarBizDto = stockCarBizMap.get(carDto.getCarId());
                if (null != carDto.getOperationType()) {
                    if (MaintenanceUserTypeEnum.USER.getValue() == carDto.getUserType()) {
                        UserBizDto user = userBizService.getUser(carDto.getUserId());
                        if (null != user) {
                            carDto.setOperationName(user.getRealName());
                        }
                    } else if (MaintenanceUserTypeEnum.OP.getValue() == carDto.getUserType()) {
                        AccountDto accountDto = accountService.getById(Integer.parseInt(carDto.getOperationId()));
                        if (null != accountDto) {
                            carDto.setOperationName(accountDto.getRealName());
                        }
                    }
                }
                if (stockCarBizDto != null) {
                    if (stockCarBizDto.getStockType().equals(StockCarStockTypeEnum.ENTREPOT_STORAGE.getValue())) {
                        carDto.setStockName("茉莉-" + stockCarBizDto.getStockName());
                        carDto.setStock(StockEnum.STOCK.getValue());
                    } else {
                        Integer userId = carDto.getUserId();
                        DealerStoreInfoBizDto dealerStoreInfoBizDto = storeBizService.getDealerStoreInfo(stockCarBizDto.getStoreId());
                        if (userId != null) {
                            if (null != carDto.getUserType()) {
                                if (MaintenanceUserTypeEnum.USER.getValue() == carDto.getUserType()) {
                                    UserBizDto user = userBizService.getUser(userId);
                                    if (null != dealerStoreInfoBizDto) {
                                        carDto.setStockName(dealerStoreInfoBizDto.getDealerShortName() + "-" + user.getRealName());
                                    }
                                    carDto.setStock(StockEnum.USER.getValue());
                                    carDto.setUserAccount(user.getName());
                                    carDto.setRealName(user.getRealName());
                                    carDto.setPhone(user.getPhone());
                                    carDto.setIdNumber(user.getIdNumber());
                                } else {
                                    AccountDto accountDto = accountService.getById(userId);
                                    if (null != accountDto) {
                                        if (null != dealerStoreInfoBizDto) {
                                            carDto.setStockName(dealerStoreInfoBizDto.getDealerShortName() + "-" + accountDto.getRealName());
                                        }
                                        carDto.setStock(StockEnum.USER.getValue());
                                        carDto.setUserAccount(accountDto.getAccount());
                                        carDto.setRealName(accountDto.getRealName());
                                        carDto.setPhone(accountDto.getUserPhone());
                                    }
                                }
                            } else {
                                UserBizDto user = userBizService.getUser(userId);
                                if (null != dealerStoreInfoBizDto) {
                                    carDto.setStockName(dealerStoreInfoBizDto.getDealerShortName() + "-" + user.getRealName());
                                }
                                carDto.setStock(StockEnum.USER.getValue());
                                carDto.setUserAccount(user.getName());
                                carDto.setRealName(user.getRealName());
                                carDto.setPhone(user.getPhone());
                                carDto.setIdNumber(user.getIdNumber());
                            }
                        } else {
                            try {
                                if (null != dealerStoreInfoBizDto) {
                                    carDto.setStockName(dealerStoreInfoBizDto.getDealerShortName() + "-" + dealerStoreInfoBizDto.getStoreShortName());
                                    carDto.setStock(StockEnum.DEALER.getValue());
                                    carDto.setDealerName(dealerStoreInfoBizDto.getDealerShortName());
                                    DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(dealerStoreInfoBizDto.getDealerId());
                                    if (null != dealerDetailDto) {
                                        carDto.setResponsibleName(dealerDetailDto.getResponsibleName());
                                        carDto.setResponsiblePhone(dealerDetailDto.getResponsiblePhone());
                                    }
                                }
                            } catch (Exception e) {
                                logger.error("查询门店信息异常");
                            }
                        }
                    }
                }
            }
        }
        Map<Integer, List<VehiclePictureDto>> pictureMap = vehiclePictureService.getVehiclePictureByVehicleIds(vehicleIds);
        if (null != pictureMap) {
            for (MaintenanceBizVo carDto : maintenanceBizVoList) {
                if (null != pictureMap.get(carDto.getVehicleId())) {
                    for (VehiclePictureDto vehiclePictureDto : pictureMap.get(carDto.getVehicleId())) {
                        if (vehiclePictureDto.getIsWhiteBg() && 1 == vehiclePictureDto.getPicDetailType()) {
                            carDto.setVehicleImg(vehiclePictureDto.getServerUrl());
                            break;
                        }

                    }
                }
            }
        }
    }

    /**
     * 保养分页
     *
     * @param map
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Paged<MaintenanceConfigVo> getMaintenanceConfigPage(Map<String, Object> map, Integer pageNum, Integer pageSize) {
        Paged<MaintenanceConfigDto> maintenanceConfigPage = maintenanceConfigService.getMaintenanceConfigPage(map, pageNum, pageSize);
        List<MaintenanceConfigDto> list = maintenanceConfigPage.getList();
        if (null == list || list.size() < 1) {
            return new Paged<MaintenanceConfigVo>();
        }

        List<Integer> vehicleIdList = new ArrayList<>();
        for (MaintenanceConfigDto maintenanceConfigDto : list) {
            Integer vehicleId = maintenanceConfigDto.getVehicleId();
            vehicleIdList.add(vehicleId);
        }
        Map<Integer, String> vehicleMap = vehicleBizService.getVehicleFullName(vehicleIdList);

        List<MaintenanceConfigVo> voList = Convert.toMaintenanceConfigVoList(list, vehicleMap);
        return new Paged<MaintenanceConfigVo>(voList, maintenanceConfigPage.getTotal(), pageSize);
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @Override
    public MaintenanceConfigVo getMaintenanceConfig(Integer id) {
        MaintenanceConfigDto maintenanceConfigDto = maintenanceConfigService.getMaintenanceConfigById(id);
        if (null == maintenanceConfigDto) {
            return null;
        }

        String vehicleName = vehicleBizService.getVehicleName(maintenanceConfigDto.getVehicleId());
        return Convert.toMaintenanceConfigVo(maintenanceConfigDto, vehicleName);
    }

    /**
     * 添加
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean createMaintenanceConfig(MaintenanceConfigCreateVo dto) {
        MaintenanceConfigCreateDto maintenanceConfigCreateDto = Convert.toMaintenanceConfigCreateDto(dto);
        maintenanceConfigService.createMaintenanceConfig(maintenanceConfigCreateDto);
        return true;
    }

    /**
     * 修改
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean modifyMaintenanceConfig(MaintenanceConfigModifyVo dto) {
        MaintenanceConfigModifyDto maintenanceConfigModifyDto = Convert.toMaintenanceConfigModifyDto(dto);
        return maintenanceConfigService.modifyMaintenanceConfig(maintenanceConfigModifyDto);
    }



}
